const statusMap = {
  0:'初始化',  
  1:'已获取账号Local，使用LocalStorage登录',
  2:'已获取账号Local，使用LocalStorage登录失败',
  3:'已获取账号Local，使用账号密码登录',
  4:'登录成功，需要切换账号'
}

setTimeout(async () => {
  const isLogin = getIslogin()
  const token = localStorage.getItem('token')
  // 初始化
  const status = await GetAccountStatus()
  console.log('当前步骤',status,statusMap[status])

  // 登录逻辑 这里就是登录页
  if(window.location.href.indexOf('https://identity.hapag-lloyd.cn/') != -1){
    console.log('登录页')
    await setStatus(3)
    // await setAccountToSession()
    // 已获取账号Local，使用账号密码登录
    // 判断是否有这种model
    const hasSelectAll = $("#accept-recommended-btn-handler")?.get(0)
    // 登录form
    const loginForm = $("#localAccountForm")?.get(0)
    // 登录页
    if(hasSelectAll && loginForm){
      hasSelectAll.click()
      // 设置账号到loginForm
      setAccount()
    }
  }else if(status == null){
    await setStatus(0)
    window.location.reload()
  }else if(status == 0){
    console.log('初始化初始化')
    await setAccountToSession()
    const a = await getAccountFromSession()
    await setAccountToLocal(a)
  } else if(status == 4){
    await setAccountToSession()
    const a = await getAccountFromSession()
    await setAccountToLocal(a)
  }else if(token && status == 1){
    console.log('已登录')
    // 已登录，存信息
    await saveLocalAndCookie()
  }else if(status == 1 && !token) {
    // 已获取账号Local，使用LocalStorage登录失败
    await setStatus(2)
    window.location.reload()
    console.log('已获取账号Local，使用LocalStorage登录失败')
  }else if(status == 2){
    console.log('准备跳转到登录页')
     // nav上面的 login 按钮
    const navBtn = $("#hal-navigation .hal-navigation-top-login-sign .hal-button")?.get(0)
    if(navBtn){
      // 跳转到登录页
      navBtn.click()
    }
    const ul = $('.hal-login-box-details .hal-navigation-top-child a').get(4)
    ul.click()
  }else if(status == 3){
    console.log('准备跳转到登录页')
     // nav上面的 login 按钮
    const navBtn = $("#hal-navigation .hal-navigation-top-login-sign .hal-button")?.get(0)
    if(navBtn){
      // 跳转到登录页
      navBtn.click()
    }
    const ul = $('.hal-login-box-details .hal-navigation-top-child a').get(4)
    ul.click()
  }


  clearTimer()
  
  
}, 3000)
const GetAccountStatus = async () => {
  const ob = await session.get('accountStatus' ,'{}')
  return JSON.parse(ob).s
}
const getIslogin = () => {
  const idk = localStorage.getItem('msal.account.keys')
  if(!idk){
    return false
  }
  console.log('idk',idk)
  const key = JSON.parse(idk)[0] || ''
  if(!key){
    return false
  }
  console.log('key',key)
  const idf = JSON.parse(localStorage.getItem(key))
  console.log('idf',idf)
  return !!idf
}
const setAccountToLocal = async (ac) => {
  console.log(ac)
  if(!ac){
    return console.error('没有获取到账号信息!')
  }
  const { otherCache } = ac
  if(otherCache) {
    const obj = JSON.parse(otherCache) 
    const local = obj.localStorage
    console.log('插入local',local)
    
    for (const key in local) {
      localStorage.setItem(key, local[key])
    }
    console.log('存入本地的localStorage',window.localStorage)
    const c = obj.cookies
    console.log('插入cookies',c)
    //设置localStorage 到 目标网站域
    // let message = {"from": "extenstion", "action": "localStorage_set", data: local};
    // window.postMessage(message, "*");

    //设置cookies 到 目标网站域
    sendMsg({action: 'setCookie', data: c})

    setTimeout(async() => {
      await setStatus(1)
      window.location.reload();
    }, 3000);
  }else{
    // 没有otherCache 直接扭转
    setTimeout(async() => {
      await setStatus(2)
      window.location.reload();
    }, 1000);
  }
}
const getAccountAndRefreshAccount = async (ac) => {
  if(!ac){
    return console.error('没有获取到账号信息!')
  }
  await setStatus(3)
  // const { apiToken, otherCache } = ac
  console.log(ac,123123)
}
const setStatus = async (s) => {
  return await session.set('accountStatus',JSON.stringify({s}))
}
const saveLocalAndCookie = async () => {
  // 登录成功刷新cookie
  sendMsg({action:"getCookie",domain:'.hapag-lloyd.cn'})
  console.log('登录成功！！！！！！！！！！！！')
  const a = await getAccountFromSession()
  let local = {}
  for (const key in window.localStorage) {
    const v = localStorage.getItem(key)
    if(v){
      local[key] = v
    }
  }
  setTimeout( async () => {
    const cc = await session.get("cookies", '[]')
    console.log('获取cookies',cc)
    const pamams = {
      ...a,
      otherCache:JSON.stringify({
        localStorage:local,
        cookies:cc,
      }),
      apiToken: JSON.stringify({
        __RequestVerificationToken: '',
        Cookie: ''
      }),
    }
    // 更新账户
    core.updateAccount(pamams)
  }, 10000);
    // 成功以后切换账号
    // 清空
  setTimeout(() => {
    window.localStorage.clear()
    // clearCookies()
    console.log('清空local',window.localStorage)
    console.log('清空cookies',document.cookie)
  }, 17000);
  setTimeout(async () => {
    console.log('准备切换账号')
    await setStatus(4)
    window.location.reload()
  }, 20000);
}
const setAccountToSession = async () => {
  await session.remove('accountFromServer')
  const res = core.getAccount('HPL-TOKEN保活插件_1', 'hpl', 'zc_pc_01');
  console.log('当前账号====>',res)
  await session.set('accountFromServer', JSON.stringify(res))
}

// 删除cookie
const clearCookies = () => {
  var cookies = document.cookie.split(";");
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    var eqPos = cookie.indexOf("=");
    var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
  }
}

// 获取账号
const getAccountFromSession = async () => {
  const se = await session.get('accountFromServer','{}')
  return JSON.parse(se)
}

// 设置账号到loginForm
const setAccount = async () => {
  const account = await getAccountFromSession()
  if(!account.username){
    await setAccountToSession()
  }
  const a = await getAccountFromSession()
  const elipt = $("#signInName").get(0)
  const pwdipt = $("#password").get(0)
  elipt.value = a.username
  pwdipt.value = a.password
  const btn = $("#localAccountForm .buttons #next").get(0)
  console.log(btn,'登录btn')
  setTimeout( async () => {
    console.log('触发登录按钮')
    btn.click({})
    await setStatus(1)
    // getLoginError(a)
  }, 10000);
}
let timer = null
const getLoginError = (errorAccount) => {
  timer = setInterval(async () => {
    const errorDiv = $('.error.pageLevel p')?.get(0)
    if(errorDiv && errorDiv.innerHTML('incorrect') != -1) {
      core.updateAccount(Object.assign(errorAccount, {
        otherCache: null,
        apiToken: null,
        remark: "plugin_remark_error"
      }))
      clearTimer()
      await setAccountToSession()
      window.location.reload()
    }
  }, 2000);
}
const clearTimer = () => {
  clearInterval(timer)
  timer = null
}